package com.sun.compressutil;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.sun.lib_compress.CompressUtil;
import com.sun.lib_compress.OnCompressListener;

import java.io.File;

public class MainActivity extends AppCompatActivity {

    private ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = findViewById(R.id.imageView);

        findViewById(R.id.selectImgView).setOnClickListener(v -> {
            XXPermissions.with(this).permission(Permission.READ_EXTERNAL_STORAGE)
                    .request((permissions, all) -> {
                        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                        i.addCategory(Intent.CATEGORY_OPENABLE);
                        i.setType("image/*");
                        startActivityForResult(i, 191);
                    });
        });
    }

    private void startCompress(Uri uri) {
        CompressUtil.width(this)
                .load(uri)
                .maxSize(200)
                .compress(new OnCompressListener() {
                    @Override
                    public void onSuccess(File file) {
                        Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
                        imageView.setImageBitmap(bitmap);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 191 && resultCode == RESULT_OK) {
            Uri uri = data.getData();
            startCompress(uri);
        }
    }
}
